package com.cj.rxdo;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by cj on 2017/3/21.
 */

public class MLayout extends RelativeLayout {
    private ClickFor3sListener for3sListener;

    public MLayout(Context context) {
        this(context,null);
    }

    public MLayout(Context context, AttributeSet attrs) {
        this(context,attrs,0);
    }

    private boolean isDown=false;  //是否按下
    private volatile double start=0;  //按下时间
    private boolean hasDone=false;  //是否已经消费3s的事件
    private Subscription subscription=null;  //订阅

    public MLayout(final Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        if(event.getAction()==MotionEvent.ACTION_DOWN){
            start=0;
            isDown=true;
            another();
            hasDone=false;
        }
        if(event.getAction()==MotionEvent.ACTION_UP){
            if(start>=3&&!hasDone){
                if(for3sListener!=null){
                    for3sListener.click3();
                }
                Log.d("xx","da yu 3");
                hasDone=true;
            }else{
//                Log.d("xx","xiao yu 3");
            }
            if(subscription!=null&&!subscription.isUnsubscribed()){
               subscription.unsubscribe();
                subscription=null;
            }
            isDown=false;
        }
        return true;
    }

    public void setFor3sListener(ClickFor3sListener listener){
        for3sListener=listener;
    }

    private void another(){
        subscription=Observable.interval(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        start=aLong*0.5;
                        if(isDown&&start>=3&&!hasDone){
                            hasDone=true;
                            Log.d("xx","Da yu 3");
                            if(for3sListener!=null){
                                for3sListener.click3();
                            }
                            if(subscription!=null&&!subscription.isUnsubscribed()){
                                subscription.unsubscribe();
                                subscription=null;
                            }

                        }
                    }
                });
    }

    public interface ClickFor3sListener{
        void click3();
    }
}
